package main

// other service
import (
	"fmt"

	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/client/selector"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-micro/v2/web"
	"github.com/micro/go-plugins/registry/consul/v2"
)

var reg registry.Registry // 注册中心

func init() {
	// 服务注册 到注册中心
	reg = consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
}

// 服务与服务之间交互 可复用的代码都可以抽出来用rpc来复用
func GetServiceAddress(name string) (address string) {
	// 这里可以负载的取
	list, _ := reg.GetService()

	var services []*registry.Service

	for _, value := range list {
		services = append(services, value)
	}

	fmt.Println("services:", services)
	next := selector.RoundRobin(services)
	fmt.Println("next:", next)

	if node, err := next(); err == nil {
		address = node.Address
		fmt.Println("address:", address)
	}
	return
}

// 逻辑业务
func Call(x, y string) string {
	// 获取服务, 发现服务 服务交互
	address := GetServiceAddress("math_service")
	// 拼接url
	url := fmt.Sprintf("http://"+address+"/math/add?x=%s&y=%s", x, y)
	// request
	response, err := http.Get(url)
	if err != nil {
		return err.Error()
	}
	content, _ := ioutil.ReadAll(response.Body)
	defer response.Body.Close()
	return string(content)
}

func InitWeb() *gin.Engine {
	r := gin.Default()
	r.GET("/other/test", func(c *gin.Context) {
		content := Call(c.Query("x"), c.Query("y"))
		c.String(200, content)
	})
	return r
}

func main() {
	service := web.NewService(
		web.Name("other_service"),
		web.Address("127.0.0.1:50001"),
		web.Handler(InitWeb()),
		web.Registry(reg),
	)
	_ = service.Run()
}
